package topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class ProducerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USERNAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        //创建信道
        Channel channel = connection.createChannel();

        //声明交换机
        channel.exchangeDeclare(Constants.TOPICS_EXCHANGE, BuiltinExchangeType.TOPIC, true);

        //声明队列
        channel.queueDeclare(Constants.TOPICS_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPICS_QUEUE2, true, false, false, null);

        //绑定交换机与队列
        channel.queueBind(Constants.TOPICS_QUEUE1, Constants.TOPICS_EXCHANGE, "*.a.*");
        channel.queueBind(Constants.TOPICS_QUEUE2, Constants.TOPICS_EXCHANGE, "*.*.b");
        channel.queueBind(Constants.TOPICS_QUEUE2, Constants.TOPICS_EXCHANGE, "c.#");

        //发送消息
        String message1 = "routingKey is fff.a.bbbb";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "fff.a.bbbb", null, message1.getBytes(StandardCharsets.UTF_8));

        String message2 = "routingKey is fff.a.b";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "fff.a.b", null, message2.getBytes(StandardCharsets.UTF_8));

        String message3 = "routingKey is c.aaa";
        channel.basicPublish(Constants.TOPICS_EXCHANGE, "c.aaa", null, message3.getBytes(StandardCharsets.UTF_8));

        /**
         * 关闭连接
         */
        channel.close();
        connection.close();
    }
}
